package com.ruoyi.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;

/**
 * @author chendy
 */
@Slf4j
public class AESUtil {
    public static final AESUtil instance = new AESUtil();

    public static boolean initialized = false;

    private static String PASSWORD = "eGluZ3Vhbmd0YmI=";
    private static String ENCODE = "UTF-8";
    private static String ALGORITHM = "AES/CBC/NoPadding";
    private static String IV = "svtpdprtrsjxabcd";

    /**
     * 小程序加密信息AES
     *
     * @param content 密文
     * @return
     * @throws InvalidAlgorithmParameterException
     * @throws NoSuchProviderException
     */
    public byte[] wxDecrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
        initialize();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");

            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (NoSuchAlgorithmException e) {
            log.error("aes解密失败，NoSuchAlgorithmException",e);
        } catch (NoSuchPaddingException e) {
            log.error("aes解密失败，NoSuchPaddingException",e);
        } catch (InvalidKeyException e) {
            log.error("aes解密失败，InvalidKeyException",e);
        } catch (IllegalBlockSizeException e) {
            log.error("aes解密失败，IllegalBlockSizeException",e);
        } catch (BadPaddingException e) {
            log.error("aes解密失败， BadPaddingException ",e);
        } catch (NoSuchProviderException e) {
            log.error("aes解密失败，NoSuchProviderException",e);
        } catch (Exception e) {
            log.error("aes解密失败",e);
        }
        return null;
    }

    public static void initialize() {
        if (initialized) {
            return;
        }
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }


    /**
     * PC端密码加密
     * @param content 需要加密的内容
     * @return
     */
    public static String pcEncrypt(String content) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = content.getBytes(ENCODE);
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keySpec = new SecretKeySpec(PASSWORD.getBytes(ENCODE), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(ENCODE));
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] result = cipher.doFinal(plaintext);
            return Base64.encodeBase64String(result);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**PC密码 解密
     * @param content  待解密内容
     * @return
     */
    public static String pcDecrypt(String content) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(PASSWORD.getBytes(ENCODE), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(ENCODE));
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] result = cipher.doFinal(Base64.decodeBase64(content));
            return new String(result,ENCODE).trim(); // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args){
        String content = "qa123456";
        //加密
        String encryptResult = pcEncrypt(content);
        System.out.println("加密后：" + encryptResult);

        //解密
        String decryptResult = pcDecrypt(encryptResult);
        System.out.println("解密后：" + decryptResult);
    }
}
